package com.enzoism.springboot.dive.bis.arraylist;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable {
    // 数组元素
    protected Object[] elementData;
    // 元素个数
    protected int size;
    // 增长因子
    protected int capacityIncrement;

    //*********************构造方法*********************//
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    public Vector() {
        this(10);
    }

    public Vector(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

    //*********************操作方法*********************//
    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, size);
    }

    // 将容量修剪为数组elementData[]的当前大小
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (size < oldCapacity) {
            elementData = Arrays.copyOf(elementData, size);
        }
    }

    // 如有必要，增加此向量的容量，以确保它至少可以容纳由最小容量参数指定的组件数量。
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

    // 容量扩容
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    // 要分配的数组的最大大小
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    // 数组容量扩容
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    // 最大容量：近似等于Integer.MAX_VALUE
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

    // 设置大小，如果小于newSize，就移除后面的元素
    public synchronized void setSize(int newSize) {
        modCount++;
        if (newSize > size) {
            ensureCapacityHelper(newSize);
        } else {
            for (int i = newSize; i < size; i++) {
                elementData[i] = null;
            }
        }
        size = newSize;
    }

    // 数组的容量【数组扩容的大小】
    public synchronized int capacity() {
        return elementData.length;
    }

    // 数组的元素个数
    public synchronized int size() {
        return size;
    }

    // 是否为空
    public synchronized boolean isEmpty() {
        return size == 0;
    }


    // 是否包含对象
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

    // 对象的索引
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    // 对象的索引
    public synchronized int indexOf(Object o, int index) {
        if (o == null) {
            for (int i = index; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index; i < size; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    // 下一个对象索引
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, size -1);
    }

    // 下一个对象索引
    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(index + " >= "+ size);

        if (o == null) {
            for (int i = index; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    // 指定位置的元素
    public synchronized E elementAt(int index) {
        if (index >= size) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + size);
        }

        return elementData(index);
    }

    // 第一个元素
    public synchronized E firstElement() {
        if (size == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

    // 最后一个元素
    public synchronized E lastElement() {
        if (size == 0) {
            throw new NoSuchElementException();
        }
        return elementData(size - 1);
    }

    // 更新指定位置元素
    public synchronized void setElementAt(E obj, int index) {
        if (index >= size) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                    size);
        }
        elementData[index] = obj;
    }

    // 移除指定位置上的元素
    public synchronized void removeElementAt(int index) {
        modCount++;
        if (index >= size) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                    size);
        }
        else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        int j = size - index - 1;
        if (j > 0) {
            System.arraycopy(elementData, index + 1, elementData, index, j);
        }
        size--;
        elementData[size] = null; /* to let gc do its work */
    }

    // 指定位置添加元素
    public synchronized void insertElementAt(E obj, int index) {
        modCount++;
        if (index > size) {
            throw new ArrayIndexOutOfBoundsException(index
                                                     + " > " + size);
        }
        ensureCapacityHelper(size + 1);
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = obj;
        size++;
    }

    // 添加元素
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(size + 1);
        elementData[size++] = obj;
    }

    // 移除指定元素
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

    // 移除所有元素
    public synchronized void removeAllElements() {
        modCount++;
        // Let gc do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;

        size = 0;
    }

    // 对象clone
    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
                Vector<E> v = (Vector<E>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    // 转化为数组
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, size);
    }

    // 将vector转化为数组，大小够直接返回，不够就返回新数组
    @SuppressWarnings("unchecked")
    public synchronized <T> T[] toArray(T[] a) {
        if (a.length < size)
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());

        System.arraycopy(elementData, 0, a, 0, size);

        if (a.length > size)
            a[size] = null;

        return a;
    }

    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    // 获取元素
    public synchronized E get(int index) {
        if (index >= size)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

    // 替换元素
    public synchronized E set(int index, E element) {
        if (index >= size)
            throw new ArrayIndexOutOfBoundsException(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    // 添加元素
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(size + 1);
        elementData[size++] = e;
        return true;
    }

    // 删除指定元素
    public boolean remove(Object o) {
        return removeElement(o);
    }

    // 添加元素
    public void add(int index, E element) {
        insertElementAt(element, index);
    }

    // 删除指定元素
    public synchronized E remove(int index) {
        modCount++;
        if (index >= size)
            throw new ArrayIndexOutOfBoundsException(index);
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work

        return oldValue;
    }

    // 删除所有元素
    public void clear() {
        removeAllElements();
    }

    // 如果此 Vector 包含指定 Collection 中的所有元素，则返回 true。
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

    //  Collection 中的所有元素附加到此 Vector 的末尾
    public synchronized boolean addAll(Collection<? extends E> c) {
        modCount++;
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(size + numNew);
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    // 从Vector 中删除包含在指定 Collection 中的所有元素。
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

    // 从Vector 中删除其所有未包含在指定 Collection 中的元素。
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }


    public synchronized boolean addAll(int index, Collection<? extends E> c) {
        modCount++;
        if (index < 0 || index > size)
            throw new ArrayIndexOutOfBoundsException(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(size + numNew);

        int numMoved = size - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,
                             numMoved);

        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

    // 移除范围内元素
    protected synchronized void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved);

        // Let gc do its work
        int newElementCount = size - (toIndex-fromIndex);
        while (size != newElementCount)
            elementData[--size] = null;
    }

    @Override
    public synchronized void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int elementCount = this.size;
        for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public synchronized boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        int removeCount = 0;
        final int size = this.size;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    @Override
    @SuppressWarnings("unchecked")
    public synchronized void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    @SuppressWarnings("unchecked")
    @Override
    public synchronized void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

}
